#include <func.h>

#define MAXLEN 256

int main(int argc,char* argv[])
{
    int fd1 = open("./pipe1-2",O_RDONLY);
    if(fd1 == -1)
        error(1,errno,"open fd1");

    int fd2 = open("./pipe2-1",O_WRONLY);
    if(fd2 == -1)
        error(1,errno,"open fd2");

    char WriteMessage[MAXLEN];
    char ReadMessage[MAXLEN];

    printf("connact succesd!\n");

    fd_set mainfds;
    FD_ZERO(&mainfds);
    FD_SET(STDIN_FILENO,&mainfds);
    
    int maxfds = STDIN_FILENO;
    FD_SET(fd1,&mainfds);
    if(fd1 > maxfds)
        maxfds = fd1;

    for(;;)
    {
        fd_set readfds = mainfds;

        int event = select(maxfds + 1,&readfds,NULL,NULL,NULL);
        switch(event)
        {
            case -1:
                error(1,errno,"select");
            case 0:
                printf("time out");
                continue;
            default:
                if(FD_ISSET(STDIN_FILENO,&readfds))
                {
                    fgets(WriteMessage,MAXLEN,stdin);
                    write(fd2,WriteMessage,strlen(WriteMessage)+1);
                }
                if(FD_ISSET(fd1,&readfds))
                {
                    int nbytes = read(fd1,ReadMessage,MAXLEN);
                    if(nbytes == 0)
                        goto end;
                    else if(nbytes == -1)
                        error(1,errno,"read pipe1");

                    printf("from 1 >>:%s",ReadMessage);
                }
                break;
        }
    }

end:
    close(fd1);
    close(fd2);

    return 0;
}
